package com.qingcloud.common.auth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingcloud.base.pojo.AjaxResult;
import com.qingcloud.common.auth.model.Client;
import com.qingcloud.common.auth.model.dto.ClientDTO;
import com.qingcloud.common.auth.service.OauthClientDetailService;
import com.qingcloud.base.pojo.Result;
import com.qingcloud.common.auth.util.AuthUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "oauth2应用调用方")
@RestController
@RequestMapping("/clients")
public class ClientController {
    @Autowired
    private OauthClientDetailService clientService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "应用列表")
    public Page<Client> list(@RequestBody ClientDTO dto) {
        return clientService.listClient(dto, true);
    }

    @GetMapping(value ="/getClients/{id}")
    @ApiOperation(value = "根据id获取应用")
    public Client getClients(@PathVariable Long id) {
        return clientService.getById(id);
    }

    @GetMapping(value ="/getClientByClientId/{clientId}")
    @ApiOperation(value = "根据id获取应用")
    public Client getClients(@PathVariable("clientId") String clientId) {
        return clientService.loadClientByClientId(clientId);
    }

    @GetMapping(value ="/getAll")
    @ApiOperation(value = "所有应用")
    public AjaxResult allClient() {
        Page<Client> page = clientService.listClient(null, false);
        return AjaxResult.success(page);
    }

    @GetMapping(value ="/deleteClient")
    @ApiOperation(value = "删除应用")
    public void delete(@RequestParam String ids) {
        if(ids !=null){
            String[] idStr = ids.split(",");
            if(idStr != null  && ids.length()>0){
                for(String id : idStr){
                    Long idInt  = Long.parseLong(id.strip());
                    clientService.delClient(idInt);
                }
            }
        }
    }

    @PostMapping(value ="/saveOrUpdate")
    @ApiOperation(value = "保存或者修改应用")
    public Result<Client> saveOrUpdate(@RequestBody Client client) throws Exception {
        return clientService.saveClient(client);
    }

    @GetMapping(value ="/getClientIdByAccessToken")
    @ApiOperation(value = "保存或者修改应用")
    public Result<String>  getClientIdByAccessToken(@RequestParam String accessTokenValue){
        return Result.success(AuthUtils.getClientIdByAccessToken(accessTokenValue));
    }
}
